import pgzrun
from vec import *
import random
import time

WIDTH = 600
HEIGHT = 440

BACK_COLOR = (0, 0, 0)
PEN_COLOR = (0, 200, 0)

lastUpdateTime = 0
lastTime = 0
nps=0
t=0.1

def FPS():
    global lastTime, lastUpdateTime
    accumTime = time.time() - lastUpdateTime
    t = time.time() - lastTime
    lastTime = time.time()
    fps=math.floor(1 / t)
    if accumTime > 1:
        lastUpdateTime = time.time()
    return fps

class PointTail:
    def __init__(self):
        self.tail = []

    def UpdatePoint(self, x, y):
        for i in range(self.count - 2, -1, -1):
            self.tail[i + 1].x = self.tail[i].x
            self.tail[i + 1].y = self.tail[i].y
        self.tail[0].x = x
        self.tail[0].y = y

    def InitPoints(self, n):
        self.count = n
        self.v=Vec2(0,0)
        self.v.x = random.randint(-5, 5)
        self.v.y = random.randint(-5, 5)
        self.v.normalize()
        px = random.randint(0, WIDTH - 1)
        py = random.randint(0, HEIGHT - 1)
        for i in range(self.count):
            self.tail.append(Vec2(px, py))

    def GetPoint(self, index):
        return self.tail[index]

    def Update(self):
        global t
        fps=int(FPS()*t//60)
        newX = self.tail[0].x + (fps+self.v.x)
        newY = self.tail[0].y + (fps+self.v.y)
          
        if newX >= WIDTH - 1:
            newX = WIDTH - 1
            self.v.x *= -1
        elif newX <= 0:
            newX = 0
            self.v.x *= -1
        if newY >= HEIGHT - 1:
            newY = HEIGHT - 1
            self.v.y *= -1
        elif newY <= 0:
            newY = 0
            self.v.y *= -1
        self.UpdatePoint(newX, newY)
        
pointCount = 4
p = []
for i in range(pointCount):
    pt = PointTail()
    pt.InitPoints(5)
    p.append(pt)

def update():
    print(FPS())
    for i in range(0, pointCount):
        p[i].Update()

def draw():
    screen.clear()
    screen.fill(BACK_COLOR)

    for i in range(0, pointCount):
        for j in range(0, p[i].count):
            if i == pointCount - 1:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[0].GetPoint(j).raw_get(), PEN_COLOR)
            else:
                screen.draw.line(p[i].GetPoint(j).raw_get(), p[i + 1].GetPoint(j).raw_get(), PEN_COLOR)

pgzrun.go()